<template>
  <!-- 自定义页面容器 -->
  <div class="app-container">
    <!-- 头部容器，用于放置各种查询筛选条件 -->
    <div class="head-container">
      <!-- 标题部分 -->
      <div class="yzlb">
        治疗师列表 &nbsp;
        <!-- 绑定治疗师名称的输入框，用于按治疗师名称查询 -->
        <el-input v-model="args.doctorName" placeholder="治疗师名称" class="width-200" />
      </div>
      <!-- 查询按钮，点击执行查询操作 -->
      <el-button type="primary" class="left-btn" @click="inquireBtn()">查询</el-button>
      <el-button type="primary" class="right-btn" @click="addDoctor">新增治疗师</el-button>
    </div>
    <!-- 表格组件，用于展示数据 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" class="left-table" :cell-style="cellStyle"
      :header-cell-style="{ background: '#eef1f6', color: '#606266', textAlign: 'center' }" border>
      <!-- 治疗师ID列 -->
      <el-table-column prop="id" label="治疗师id" width="80" />
      <el-table-column prop="therapistName" label="治疗师姓名" />
      <el-table-column prop="gender" label="性别" width="55">
        <template #default="{ row }">{{ getGenderText(row.gender) }}</template>
      </el-table-column>
      <el-table-column prop="phoneNum" label="联系电话" />
      <el-table-column prop="idCard" label="身份证号" />
      <el-table-column prop="departmentName" label="科室名称" />
      <el-table-column prop="departmentCode" label="科室编码" />
      <el-table-column prop="doctorSynopsis" label="简介" />
      <el-table-column prop="therapistStates" label="治疗师状态" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.therapistStates" :active-value="1" :inactive-value="0" disabled />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <!-- 编辑按钮，点击可执行编辑相关逻辑（此处暂未实现具体逻辑） -->
          <el-link type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-link>
          <!-- 删除按钮，点击可执行删除相关逻辑（此处暂未实现具体逻辑） -->
          <el-link type="danger" size="mini" @click="handleDelete(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false"
      @close="clearFormValidate">
      <el-form :model="editForm" label-width="100px" :rules="editRules" ref="editFormRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="治疗师姓名" prop="therapistName" :rules="editRules.therapistName">
              <el-input v-model="editForm.therapistName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phoneNum" :rules="editRules.phoneNum">
              <el-input v-model="editForm.phoneNum" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard" :rules="editRules.idCard">
              <el-input v-model="editForm.idCard" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="科室名称">
              <el-select v-model="editForm.departmentName" placeholder="请选择科室" @change="updateDepartmentCode">
                <el-option v-for="(code, name) in departmentMap" :key="name" :label="name" :value="name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室编码">
              <el-input v-model="editForm.departmentCode" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="治疗师状态">
              <el-switch v-model="editForm.therapistStates" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="简介">
              <el-input v-model="editForm.doctorSynopsis" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="isAdd" type="primary" @click="handleAddEdit('editFormRef')">保存</el-button>
        <el-button v-if="isEdit" type="primary" @click="handleSaveEdit('editFormRef')">保存编辑</el-button>
      </div>
    </el-dialog>
    <!-- 分页组件，用于数据分页展示 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="args.page"
      :page-sizes="[10, 20, 30, 50]" :page-size="args.size" layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import { queryAllTherapistInfo, updateTherapistInfo, deleteTherapistInfo, addTherapistInfo, queryDepartment } from "@/api/schedule/doctorManagement/info.js"
export default {
  name: "doctorPage",
  data() {
    return {
      // 查询参数对象，用于存放各种查询条件及分页相关参数
      args: {
        doctorName: "", // 用于存储输入的治疗师名称，用于查询
        page: 1, // 当前页码
        size: 10, // 每页显示的数据条数
      },
      // 表格数据数组，存放要展示的数据
      resData: [],
      tableData: [],
      total: 0, // 数据总条数，用于分页计算
      loading: false,
      dialogVisible: false, // 编辑对话框是否可见
      //对话标题
      dialogTitle: '', // 用于控制对话框标题的属性
      isAdd: false, //控制新增按钮显示
      isEdit: false,//控制更新按钮显示
      editForm: {}, // 编辑表单数据
      genderOptions: [
        { value: 0, label: '女' },
        { value: 1, label: '男' }
      ],
      departmentMap: {}, // 用于存储科室名称与编码的映射
      editRules: {
        therapistName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' }
        ],
        phoneNum: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
      },
    };
  },
  methods: {
    // 处理每页显示条数变化的逻辑
    handleSizeChange(val) {
      this.args.size = val;
      // 此处可添加重新获取数据的逻辑，如调用接口获取对应条数的数据，目前仅更新参数
      this.getList();
    },
    // 处理当前页码变化的逻辑
    handleCurrentChange(val) {
      this.args.page = val;
      // 此处可添加重新获取数据的逻辑，如调用接口获取对应页码的数据，目前仅更新参数
      this.getList();
    },
    // 查询按钮点击执行的方法，重置页码并获取数据
    inquireBtn() {
      this.args.page = 1;
      this.getList();
    },
    // 获取数据列表的方法
    async getList() {
      // 请求查询数据接口
      this.loading = true; // 设置为加载状态
      try {
        let res = await queryAllTherapistInfo({
          page: this.args.page,
          size: this.args.size,
          therapistName: this.args.doctorName
        });
        // 更新总记录数，用于分页组件计算总页数
        this.total = res.totalElements;
        this.resData = res.content.map((i) => ({ ...i }));
        console.log(this.resData, "resData");
        this.tableData = this.resData;
      } finally {
        setTimeout(() => {
          this.loading = false;
        }, 300)
      }
    },
    // （点击新增治疗师）添加记录
    addDoctor() {
      this.dialogTitle = '新增治疗师信息';
      this.dialogVisible = true;
      this.editForm = {};
      // 设置为新增记录状态，显示新增按钮
      this.isAdd = true;
      this.isEdit = false;
      // this.resetForm();
    },
    //(点击保存)
    async handleAddEdit(editFormRef) {
      try {
          const valid = await this.$refs[editFormRef].validate();
          if (valid) {
          console.log('提交信息：', this.editForm);
          addTherapistInfo(this.editForm)
            .then(response => {
              // 根据接口返回处理成功情况，比如提示用户新增成功等
              console.log("记录新增成功：", response);
              this.$notify({
                title: '提示',
                message: '记录保存成功',
                type: 'success'
              });
              // 关闭弹窗
              this.editDialogVisible = false;
              // 重新获取数据刷新表格
              this.getList();
            })
          this.dialogVisible = false;
          this.getList();
        } else {
          // 验证不通过，不调用接口，弹窗不隐藏，这里已经会自动显示红色提示消息（由表单验证规则控制）
          return false;
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    // （点击编辑）按钮执行的方法
    async handleEdit(row) {
      this.dialogTitle = '编辑治疗师信息';
      this.isAdd = false;
      this.isEdit = true;
      console.log(`编辑治疗师，ID为：${row.id}`);
      this.dialogVisible = true;
      this.editForm = {
        id: row.id,
        therapistName: row.therapistName,
        gender: row.gender,
        phoneNum: row.phoneNum,
        idCard: row.idCard,
        departmentName: row.departmentName,
        departmentCode: row.departmentCode,
        doctorSynopsis: row.doctorSynopsis,
        therapistStates: row.therapistStates,
      };
    },
    // （点击保存编辑）的方法
    async handleSaveEdit(editFormRef) {
      try {
        const valid = await this.$refs[editFormRef].validate(); // 假设ref名为editFormRef，先获取验证结果
        if (valid) {
          await updateTherapistInfo({ ...this.editForm });
          this.dialogVisible = false;
          this.$notify({
            type: 'success',
            message: '编辑成功'
          });
          this.getList();
        } else {
          // 验证不通过，不调用接口，弹窗不隐藏，这里已经会自动显示红色提示消息（由表单验证规则控制）
          return false;
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    // 删除按钮点击执行的方法
    async handleDelete(id) {
      try {
        await this.$confirm('确定要删除该治疗师信息吗？此操作不可恢复。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await deleteTherapistInfo({ id });
          this.$message({
            type: 'success',
            message: '治疗师信息删除成功'
          });
          // this.args.page = 1;
          this.getList();
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除操作'
          });
        });
      } catch (error) {
        this.$message({
          type: 'danger',
          message: '删除失败，请稍后再试'
        });
        console.log(error, "error");
      }
    },
    // 根据性别代码获取性别文本的方法
    getGenderText(Gender) {
      switch (Gender) {
        case 0:
          return "女";
        case 1:
          return "男";
        default:
          return "";
      }
    },
    // 修改table cell样式的方法，使单元格内容居中显示
    cellStyle({ row, column, rowIndex, columnIndex }) {
      return "text-align:center;";
    },
    // 获取科室信息下拉框接口
    async queryDepartmentInfo() {
      try {
        let res = await queryDepartment();
        if (res && res.code === 0 && res.content) {
          this.departmentMap = {};
          res.content.forEach(item => {
            this.departmentMap[item.departmentName] = item.departmentCode;
          });
        }
        console.log("获取科室信息下拉框接口",res);
        
      } catch (error) {
        this.$notify({
          title: '提示',
          message: '网络出错了，请稍后再试',
          type: 'danger'
        });
      }
    },
    // 根据选择的科室名称更新科室编码的方法
    updateDepartmentCode() {
      this.editForm.departmentCode = this.departmentMap[this.editForm.departmentName];
    },

    //关闭dialog时调用的方法
    clearFormValidate() {
      this.$refs.editFormRef.clearValidate();
    },

  },
  mounted() {
    this.getList();
    this.queryDepartmentInfo();
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: #fff;
  padding: 5px;

  .width-100 {
    width: 100px;
  }

  .width-150 {
    width: 150px;
  }

  .width-180 {
    width: 180px;
  }

  .width-200 {
    width: 200px;
  }

  .width-230 {
    width: 230px;
  }

  .width-260 {
    width: 260px;
  }

  .head-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .yzlb {
      font-weight: 600;
      margin-right: 10px;
    }

    .left-select,
    .left-btn {
      margin-left: 10px !important;
    }

    .right-btn {
      margin-left: auto !important;
    }
  }


  .el-link {
    margin: 0px 5px;
  }

  .el-pagination {
    text-align: center;
    margin-top: 8px;
  }
}
</style>